//
//  YXOauthViewController.swift
//  yanXiangWeiBo
//
//  Created by 颜祥 on 15/12/22.
//  Copyright © 2015年 yanxiang. All rights reserved.
//

import UIKit
import SVProgressHUD

class YXOauthViewController: UIViewController,UIWebViewDelegate
{
    // 加载webView
    override func loadView() {
        view = webView
        
        // 设置代理,监听webView加载的过程
        webView.delegate = self
        
    }
    
    
    //MARK: - 监听webView加载的过程
    // webView开始加载
    func webViewDidStartLoad(webView: UIWebView)
    {
        
        SVProgressHUD.showWithStatus("正在加载中...", maskType: SVProgressHUDMaskType.Black)
    }
    
    // webView加载完成
    func webViewDidFinishLoad(webView: UIWebView)
    {
        SVProgressHUD.dismiss()
        
    }
    
    // webView开始加载响应
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        let url = request.URL?.absoluteString
        
        print("url:\(url)")
        
        // 只有点击取消或授权才会去加载授权回调地址，其他情况不会加载
        // 不是授权回调地址，直接加载
        if url?.hasPrefix(YXNetWorkTool.sharedInstance.redirect_uri) == false
        {
            return true
        }
        
        // 点击授权:http://www.baidu.com/?code=75c9b9534f80d90695d03f160999e9e5
        // 点击取消:http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // 判断是点击授权还是点击取消
        // 获得url?后面的内容
        if let query = request.URL?.query
        {
            let codeString = "code="
            
            // 如果query是以"code="开头，点击的是"授权"
            if query.hasPrefix(codeString)
            {
                // 截取code
                // 将query转换成NSString
                let queryNS = query as NSString
                
                // 截取code
                let code = queryNS.substringFromIndex(codeString.characters.count)
                
                print("code:\(code)")
                
                // 加载accessToken
                loadAccessToken(code)
                
                
            }else //点击的是"取消"
            {
                // 关闭控制器
                self.close()
            }
            
            
            
        }else
        {
            print("query没有值")
        }
        
        
        return false
    }
    
    // MARK:- 根据截取的code来加载accessToken
    func loadAccessToken(code: String)
    {
        YXNetWorkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            
            // 判断网络请求是否有错误
            if result == nil && error != nil
            {
                print("error:\(error)")
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
                // 延迟1s后关闭授权控制器
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    
                    // 关闭授权控制器
                    self.close()
                })
                
                return
                
            }
            
            // 加载accessToken成功
            // 字典转模型
            let userAccount = YXUserAccount(dict: result!)
            
            // 保存帐户对象到沙盒
            userAccount.saveUserAccount()
            
            print("userAccount:\(userAccount)")
            
            // 切换到欢迎界面
            (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
            
            // 关闭登录界面
            self.close()
            
        }
    }
    
    
    
    
    //MARK:- 加载新浪提供的登录界面
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        
        // 加载新浪提供的登录界面
        let url = YXNetWorkTool.sharedInstance.oAuthURL()
        
        let request = NSURLRequest(URL: url)

        webView.loadRequest(request)
        
        // 设置导航条两边的按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.title = "登录"
        
    }
    
    // MARK: - 自动填充帐号和密码
    func autoFill()
    {
        // 创建js代码
        let js = "document.getElementById('userId').value='czbkiosweibo@163.com'; document.getElementById('passwd').value='czbkios007';"
        
        // 让webView来执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    // MARK: - 关闭登录界面
    func close()
    {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    // MARK: - 懒加载webView
    private lazy var webView = UIWebView()



}
